package com.fuyao.cloud.personnel.library.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.common.biz.service.FyBaseServiceImpl;
import com.fuyao.cloud.personnel.library.entity.Book;
import com.fuyao.cloud.personnel.library.entity.BookCategory;
import com.fuyao.cloud.personnel.library.mapper.BookMapper;
import com.fuyao.cloud.personnel.library.service.BookCategoryService;
import com.fuyao.cloud.personnel.library.service.BookService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class BookServiceImpl extends FyBaseServiceImpl<BookMapper, Book> implements BookService {

    private final BookCategoryService bookCategoryService;

    @Transactional(propagation = Propagation.NESTED)
    @Override
    public boolean importData(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Book.class, new PageReadListener<Book>(books -> {
            books.forEach(book -> {
                book.setTenantId(null);
                book.setUnid(IdUtil.simpleUUID());
                String catalogCode = book.getCatalogCode();
                if (StrUtil.isNotBlank(catalogCode)) {
                    catalogCode = StrUtil.removePrefix(catalogCode, "/");
                    String[] segments = catalogCode.split("/");
                    if (segments.length > 0) {
                        BookCategory parent = null;
                        BookCategory child;
                        for (int i = 0; i < segments.length; i++) {
                            String segment = segments[i];

                            String fullCode = Arrays.stream(segments).limit(i + 1).collect(Collectors.joining("/"));

                            if (StrUtil.isBlank(fullCode)) {
                                fullCode = "/";
                            }

                            child = bookCategoryService.findByFullCode(fullCode);

                            if (child == null) {
                                child = bookCategoryService.create();
                                if (parent != null) {
                                    child.setParentId(parent.getId());
                                }
                                child.setName(segment);
                                child.setFullName(fullCode);
                                bookCategoryService.save(child);
                            }
                            parent = child;
                        }

                        book.setCatalogId(parent.getId());
                    }
                }

            });
            Set<String> bookCodes = baseMapper.selectList(Wrappers.<Book>lambdaQuery().in(Book::getBookCode, books.stream().map(Book::getBookCode).collect(Collectors.toSet()))).stream().map(Book::getBookCode).collect(Collectors.toSet());
            books = books.stream().filter(book -> !bookCodes.contains(book.getBookCode())).collect(Collectors.toList());
            books = CollectionUtil.distinct(books, Book::getBookCode, false);
            saveBatch(books);
        })).sheet().doReadSync();
        return true;
    }

    @Override
    public IPage<Book> selectBookPage(Page<Book> page, Book example) {
        // TODO 优化数据权限处理逻辑
        // Page<Book> bookPage = baseMapper.selectPageByScope(page, Wrappers.query(example), new DataScope());

        return baseMapper.selectBookPage(page, example);
    }
}
